package com.store.service.impl;

import com.store.entity.User;
import com.store.mapper.UserMapper;
import com.store.service.EmailService;
import com.store.service.ex.UserNotFoundException;
import com.store.util.RandomUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.annotation.Resource;

/**
 * 邮件发送业务层
 */
@DubboService(interfaceClass = EmailService.class,version = "1.0.0",timeout = 5000)
public class EmailServiceImpl implements EmailService {

    @Resource
    private UserMapper userMapper;

    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String account;


    /**
     * 实际发送
     * @param target 目标邮箱
     * @param subject 邮件主题
     * @param text 邮件内容
     */
    @Override
    public void sendEmail(String target,String subject,String text){
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom(account);
        smm.setTo(target);
        smm.setSubject(subject);
        smm.setText(text);
        javaMailSender.send(smm);
    }

    /**
     * 拼接内容
     * @param username 重置用户名
     * @param check_word 验证码
     * @return 邮件内容
     */
    @Override
    public String retrieveMess(String username, String check_word){
        StringBuilder sb = new StringBuilder();
        sb.append("亲爱的用户：\n\n");
        sb.append("您好！感谢您使用本系统，您的账号 (");
        sb.append(username);
        sb.append(") 正在进行邮箱验证，本次请求的验证码为：\n");
        sb.append(check_word);
        sb.append(" (为了保障您账号的安全性，请在90S内完成验证)");
        return sb.toString();
    }

    /**
     * 获取验证码
     * @param username 重置用户名
     * @return 验证码
     */
    @Override
    public String getCheckNum(String username) {
        User exists = userMapper.selectUserByUsername(username);
        if(exists == null){
            throw new UserNotFoundException("用户不存在");
        }else {
            //更新用户表
            //TODO
            //获取随机数作为验证码
            String check_num = RandomUtil.getRandom();
            return check_num;
        }
    }
}
